package ee.serge.client.content.cp;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;

import ee.serge.client.AlertBox;
import ee.serge.client.Header;
import ee.serge.client.Move;
import ee.serge.service.Service;
import ee.serge.util.Content;
import ee.serge.util.FormPanel;
import ee.serge.util.Loader;
import ee.serge.util.SimpleCallback;
import ee.serge.util.URLData;
import ee.serge.util.bootstrap.BButton;
import ee.serge.util.bootstrap.BButtonBar;

public class LoginContent extends Content {

   private static final String NAME = "cp/login";
   
   public static String getName() {
      return NAME;
   }
   
   public static URLData getURLData() {
      URLData data = new URLData();
      data.setName(NAME);
      return data;
   }
   
   public static void show() {
      Move.get().setContent(new LoginContent());
   }
   
   public LoginContent() {
      makeLoginPanel();
   }
   
   private FormPanel panel;
   private TextBox nameBox;
   private PasswordTextBox passwordBox;
   private void makeLoginPanel() {
      panel = new FormPanel();
      panel.add("Name", nameBox = new TextBox());
      panel.add("Password", passwordBox = new PasswordTextBox());
      add(panel);
      
      BButtonBar buttonBar = new BButtonBar();
      add(buttonBar);
      buttonBar.add(new BButton("Login", BButton.PRIMARY, new ClickHandler() {
         
         @Override
         public void onClick(ClickEvent event) {
            Loader.show();
            Service.getControlPanelService().login(nameBox.getText(), passwordBox.getText(), new SimpleCallback<Boolean>() {
               
               @Override
               public void success(Boolean result) {
                  Loader.hide();
                  if (result == true) {
                     Move.get().goToURLData(LoansPanelContent.getURLData());
                     AlertBox.showSuccess("Welcome " + nameBox.getText() + "<br>\nYou have been successfully logged in");
                     Header.getInstance().login();
                  } else {
                     AlertBox.showError("Wrong username or password<br>Both password and username are case sensitive");
                  }
               }
            });
         }
      }));
   }
   
}
